/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.security.tapestry.components;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.libermundi.theorcs.core.exceptions.ValueNotFoundException;
import org.libermundi.theorcs.core.util.JsonUtils;
import org.libermundi.theorcs.security.SecurityConstants;
import org.libermundi.theorcs.security.model.User;
import org.libermundi.theorcs.security.services.UserManager;
import org.libermundi.theorcs.security.tapestry.services.GigyaServices;
import org.libermundi.theorcs.security.util.SecurityUtils;
import org.slf4j.Logger;

import com.google.gson.JsonElement;

public class GigyaLinkAccountForm {
	@Inject
	private Logger _logger;
	
	@SessionAttribute(SecurityConstants.SESSION_GIGYA_JSON)
	private JsonElement _gigyaJson;
	
	@Inject
	private UserManager _userManager;	
	
	@Inject
	private Messages _messages;	

	@Inject
	private GigyaServices _gigyaServices;
	
	@Component
    private Form _linkAccountForm;
	
	/*------- Fields for linkAccountForm -------------*/
	@Property
	@Persist
	private String _linkUsername;
	
	@Property
	private String _linkPassword;
	
	/*------- Some Message Related Methods -------------*/
	
	public String getLegendMessage(){
		try {
			String nickName = JsonUtils.getKey(_gigyaJson, "nickname");
			String provider = JsonUtils.getKey(_gigyaJson, "loginProvider");
			return _messages.format("main.registerform.linkaccount.legend2", String.format("%s (%s)", nickName, provider));
		} catch (ValueNotFoundException e) {
			return _messages.format("main.registerform.linkaccount.legend3");
		}
	}
	
	/*------- Event Management -------------*/
	
	@OnEvent(value="validate", component="linkAccountForm")
	public void validateLinkAccount(){
		User linkUser = _userManager.getUserByUsername(_linkUsername);
		if(!SecurityUtils.isPasswordMatch(linkUser, _linkPassword)) {
			String errorMsg = _messages.get("main.registerform.linkaccount.error.accountnotfound");
			_logger.error(errorMsg);
			_linkAccountForm.recordError(errorMsg);
		}
	}
	
	@OnEvent(value="success",component="linkAccountForm")
	public String onSuccessFromLogin() {
		User linkUser = _userManager.getUserByUsername(_linkUsername);
		if(SecurityUtils.isPasswordMatch(linkUser, _linkPassword)) {
			String gigyaUid;
			try {
				gigyaUid = JsonUtils.getKey(_gigyaJson, "UID");
			} catch (ValueNotFoundException e) {
				_logger.error("GigyaUID not found ! Link association aborted.", e);
				throw new RuntimeException("GigyaUID not found ! Link association aborted.");
			}
			_gigyaServices.notifyRegistration(gigyaUid, linkUser, "Link Account");
		}
		return "Index";
	}	
}
